{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using Theano backend.\n",
      "Using gpu device 0: GeForce GT 740M (CNMeM is enabled with initial size: 80.0% of memory, cuDNN not available)\n"
     ]
    }
   ],
   "source": [
    "from keras.models import Sequential\n",
    "from keras.layers.core import Flatten, Dense, Dropout\n",
    "from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D\n",
    "from keras.optimizers import SGD\n",
    "import cv2, numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model = Sequential()\n",
    "model.add(ZeroPadding2D((1,1),input_shape=(3,224,224)))\n",
    "model.add(Convolution2D(64, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(64, 3, 3, activation='relu'))\n",
    "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
    "\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(128, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(128, 3, 3, activation='relu'))\n",
    "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
    "\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(256, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(256, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(256, 3, 3, activation='relu'))\n",
    "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
    "\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
    "\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(ZeroPadding2D((1,1)))\n",
    "model.add(Convolution2D(512, 3, 3, activation='relu'))\n",
    "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
    "\n",
    "model.add(Flatten())\n",
    "model.add(Dense(4096, activation='relu'))\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Dense(4096, activation='relu'))\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Dense(12, activation='softmax'))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\n",
    "model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=[\"accuracy\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from keras.preprocessing.image import ImageDataGenerator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "datagen = ImageDataGenerator(\n",
    "        rotation_range=40,\n",
    "        width_shift_range=0.2,\n",
    "        height_shift_range=0.2,\n",
    "        rescale=1./255,\n",
    "        shear_range=0.2,\n",
    "        zoom_range=0.2,\n",
    "        horizontal_flip=True,\n",
    "        fill_mode='nearest')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 4797 images belonging to 12 classes.\n"
     ]
    }
   ],
   "source": [
    "train_generator = datagen.flow_from_directory(\n",
    "        'data/train',\n",
    "        target_size=(224, 224),\n",
    "        batch_size=1,\n",
    "        class_mode=\"categorical\",  # this means our generator will only yield batches of data, no labels\n",
    "        shuffle=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 1115 images belonging to 12 classes.\n"
     ]
    }
   ],
   "source": [
    "test_generator = datagen.flow_from_directory(\n",
    "        'data/test',\n",
    "        target_size=(224, 224),\n",
    "        batch_size=1,\n",
    "        class_mode=\"categorical\",\n",
    "        shuffle=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/9\n",
      " 48/533 [=>............................] - ETA: 532s - loss: 12.4413 - acc: 0.1875"
     ]
    }
   ],
   "source": [
    "bottleneck_features_train = model.fit_generator(train_generator,samples_per_epoch=533,nb_epoch=9,validation_data=test_generator,nb_val_samples=1115)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model.save_weights('test_2.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "def load_image(imageurl):\n",
    "    im = cv2.resize(temp,(224,224)).astype(np.float32)\n",
    "    im[:,:,0] -= 103.939\n",
    "    im[:,:,1] -= 116.779\n",
    "    im[:,:,2] -= 123.68\n",
    "    im = im.transpose((2,0,1))\n",
    "    im = np.expand_dims(im,axis=0)\n",
    "    return im    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "import os\n",
    "from PIL import Image\n",
    "import numpy as np\n",
    "import cv2\n",
    "#读取文件夹mnist下的42000张图片，图片为灰度图，所以为1通道，\n",
    "#如果是将彩色图作为输入,则将1替换为3,图像大小28*28\n",
    "temp=0\n",
    "def load_data():\n",
    "    data = np.empty((5982,3,224,224),dtype=\"float32\")\n",
    "    label = np.empty((5982,),dtype=\"uint8\")\n",
    "\n",
    "    imgs = os.listdir(\"./test\")\n",
    "    num = len(imgs)\n",
    "    for i in range(num):\n",
    "        img=cv2.imread(\"./test/\"+imgs[i])\n",
    "        # img = load_image(\"./test/\"+imgs[i])\n",
    "        arr = np.asarray(img,dtype=\"float32\")\n",
    "        data[i,:,:,:] = arr\n",
    "        label[i] = int(imgs[i].split('.')[0])\n",
    "    return data,label"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "data, label = load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [Root]",
   "language": "python",
   "name": "Python [Root]"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
